package com.star.security.authentication;

import com.star.security.exception.AuthenticationException;
import com.star.security.exception.ProviderNotMatchingException;
import com.star.security.user.UserDetails;

import java.util.Collections;
import java.util.List;

/**
 * 提供者管理器
 *
 * @author yangzj
 */
public class AuthenticationManagerImpl implements AuthenticationManager {

    private List<AuthenticationProvider> providers = Collections.emptyList();

    private final UserDetailsChecker userDetailsChecker = new UserDetailsCheckerImpl();

    public AuthenticationManagerImpl(List<AuthenticationProvider> providers) {
        this.providers = providers;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (authentication.isAuthenticated()) {
            return authentication;
        }
        for (AuthenticationProvider provider : providers) {
            if (!provider.supports(authentication.getClass())) {
                continue;
            }
            Authentication authenticated = provider.authenticate(authentication);
            Object principal = authenticated.getPrincipal();
            userDetailsChecker.check((UserDetails) principal);
            return authenticated;
        }
        throw new ProviderNotMatchingException("没有匹配的身份验证提供者");
    }
}
